package com.simpleim.starter.server;

import com.simpleim.im.common.bean.User;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class SessionMap {

    private static final Logger log = LoggerFactory.getLogger(SessionMap.class);

    private static final SessionMap INSTANCE = new SessionMap();

    private ConcurrentHashMap<String, ServerSession> map = new ConcurrentHashMap<>();

    private SessionMap() {
    }

    public static SessionMap inst() {
        return INSTANCE;
    }

    public void addSession(ServerSession session) {
        map.put(session.getSessionId(), session);
        log.info("用户登录:id= " + session.getUser().getUid()
                + "   在线总数: " + map.size());
    }

    public void removeSession(String sessionId) {
        if (!map.containsKey(sessionId)) {
            return;
        }
        ServerSession s = map.get(sessionId);
        map.remove(sessionId);
        log.info("用户下线:id= " + s.getUser().getUid()
                + "   在线总数: " + map.size());
    }

    public ServerSession getSession(String sessionId) {
        if (map.containsKey(sessionId))
            return map.get(sessionId);
        return null;
    }

    /**
     * 根据用户id获取对应的session
     * @param userId
     * @return
     */
    public List<ServerSession> getSessionsBy(String userId) {
        if (StringUtil.isNullOrEmpty(userId))
            return new ArrayList<>();
        return map.values().stream().filter(item -> {
            return item.getUser().getUid().equals(userId);
        }).collect(Collectors.toList());
    }

    /**
     * 判断用户是否登录
     * @param user
     * @return
     */
    public boolean hasLogin(User user) {
        for (ServerSession session : map.values()) {
            User tempUser = session.getUser();
            if (tempUser.getUid().equals(user.getUid()) && tempUser.getPlatform() == user.getPlatform())
                return true;
        }
        return false;
    }
}
